package com.example.chengww.myone.fragment;


import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chengww.myone.R;
import com.example.chengww.myone.activity.MainActivity;
import com.example.chengww.myone.adapter.MyPagerAdapter;
import com.example.chengww.myone.bean.Data;
import com.example.chengww.myone.utils.BitmapUtils;
import com.example.chengww.myone.utils.HTTPUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements View.OnClickListener{

    private ViewPager viewPager;
    private ScrollView scrollView;
    private TextView hp_title,hp_author,hp_content,hp_makettime,praisenum;
    private ImageView hp_img;
    private Context context;
    private List<Data> datas;
    private List<View> views;
    private MyPagerAdapter pagerAdapter;
    //喜欢按钮计数
    private int count = 0;
    private String imgPath;
    private String LocalPath;
    private String fileName;
    //裁剪图片
//    private int width;
//    private int height;

    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 初始化
        context = getActivity();
        datas = ((MainActivity)context).getHomeDatas();
        viewPager = (ViewPager) inflater.inflate(R.layout.fragment_home, container, false);


        return viewPager;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewPager();
         pagerAdapter = new MyPagerAdapter(views);
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                imgPath = datas.get(position).getHp_img_url();
                 fileName= BitmapUtils.getFileName(imgPath);

                scrollView = (ScrollView)views.get(position);
                hp_img = (ImageView) scrollView.findViewById(R.id.hp_img_url);
                hp_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        ImageView img = new ImageView(context);
                        img.setPadding(0,0,0,0);
                        Picasso.with(context).load(imgPath).into(img);
                        builder.setView(img);
                        AlertDialog dialog = builder.create();

                        Window win = dialog.getWindow();
                        win.getDecorView().setPadding(0, 0, 0, 0);
                        WindowManager.LayoutParams lp = win.getAttributes();
                        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        win.setAttributes(lp);
                        win.setBackgroundDrawableResource(android.R.color.transparent);
                        win.setWindowAnimations(R.style.HomeImgAnimations);
                        dialog.show();
                        img.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(final View v) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                builder.setTitle("更多操作:");
                                builder.setItems(new CharSequence[]{"保存到图库", "取消"}, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case 0:
                                                //保存文件到图库
                                                BitmapUtils.insertImgStore(getActivity(), LocalPath,fileName);
                                                Toast.makeText(getActivity(),"保存成功", Toast.LENGTH_SHORT).show();
                                                break;
                                            case 1:
                                                dialog.dismiss();
                                                break;
                                        }
                                    }
                                });
                                builder.create().show();
                                return true;
                            }
                        });

                    }
                });
                hp_title = (TextView) scrollView.findViewById(R.id.hp_title);
                hp_author = (TextView) scrollView.findViewById(R.id.hp_author);
                hp_content = (TextView) scrollView.findViewById(R.id.hp_content);
                hp_makettime = (TextView) scrollView.findViewById(R.id.hp_makettime);
                praisenum = (TextView) scrollView.findViewById(R.id.praisenum);
                Picasso.with(context).load(imgPath).config(Bitmap.Config.RGB_565)
                        .transform(new Transformation() {
                            @Override
                            public Bitmap transform(Bitmap source) {
                                //保存文件到本地
                                String  path = BitmapUtils.saveImageToSDCard(source, fileName);
                                Bitmap bmp = BitmapUtils.getBitmapByPath(path);
                                LocalPath = BitmapUtils.saveImageToSDCard(bmp, fileName);
                                if (bmp!=source){
                                    source.recycle();
                                    source=null;
                                }
                                return bmp;
                            }

                            @Override
                            public String key() {
                                return imgPath;
                            }
                        })
                        .placeholder(R.mipmap.default_hp_image).error(R.mipmap.default_hp_image).into(hp_img);
                hp_title.setText(HTTPUtils.URLDecode(datas.get(position).getHp_title()));
                hp_author.setText(HTTPUtils.URLDecode(datas.get(position).getHp_author()));
                hp_content.setText(HTTPUtils.URLDecode(datas.get(position).getHp_content()));
                hp_makettime.setText(HTTPUtils.URLDecode(datas.get(position).getHp_makettime()));
                praisenum.setText(String.valueOf(datas.get(position).getPraisenum()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    private void initViewPager(){
        //获取手机屏幕宽度以裁剪图片
//        DisplayMetrics displayMetrics = new DisplayMetrics();
//        ((MainActivity)context).getWindowManager().getDefaultDisplay().
//                getMetrics(displayMetrics);
//        width = (int)(displayMetrics.widthPixels * 0.8);
//        if (1360/width > 0){
//            height = 1020/(1360/width);
//        }else {
//            height = 1020;
//        }

        views = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
                scrollView = (ScrollView) LayoutInflater.from(context).
                        inflate(R.layout.home_content,null);
            ImageView love = (ImageView) scrollView.findViewById(R.id.love);
            love.setId(i);
            love.setOnClickListener(this);
            if(i == 0){
                hp_img = (ImageView) scrollView.findViewById(R.id.hp_img_url);
                hp_title = (TextView) scrollView.findViewById(R.id.hp_title);
                hp_author = (TextView) scrollView.findViewById(R.id.hp_author);
                hp_content = (TextView) scrollView.findViewById(R.id.hp_content);
                hp_makettime = (TextView) scrollView.findViewById(R.id.hp_makettime);
                praisenum = (TextView) scrollView.findViewById(R.id.praisenum);
                Picasso.with(context).load(datas.get(0).getHp_img_url()).config(Bitmap.Config.RGB_565)
                        .placeholder(R.mipmap.default_hp_image).error(R.mipmap.default_hp_image).into(hp_img);
                hp_title.setText(HTTPUtils.URLDecode(datas.get(0).getHp_title()));
                hp_author.setText(HTTPUtils.URLDecode(datas.get(0).getHp_author()));
                hp_content.setText(HTTPUtils.URLDecode(datas.get(0).getHp_content()));
                hp_makettime.setText(HTTPUtils.URLDecode(datas.get(0).getHp_makettime()));
                praisenum.setText(String.valueOf(datas.get(0).getPraisenum()));
            }
            views.add(scrollView);
        }

    }


    @Override
    public void onClick(View v) {
        if (v instanceof ImageView){
            ImageView love = (ImageView) v;
            //点赞数
            int num = datas.get(v.getId()).getPraisenum();
            scrollView = (ScrollView)views.get(v.getId());
            praisenum = (TextView) scrollView.findViewById(R.id.praisenum);
            //偶数，点赞,点赞数加1
            if ((count & 1) != 0){
                love.setImageResource(R.mipmap.laud_selected);
                praisenum.setText(String.valueOf(num + 1));
            }else {
                love.setImageResource(R.mipmap.laud_pressed);
                praisenum.setText(String.valueOf(num));
            }
            count++;
        }

    }
}
